// pages/search/search.js
Page({
  data: {
    keyword: '',
    hotKeywords: ['租房', '二手', '兼职', '家教', '宠物'],
    searchHistory: [],
    searchResult: null
  },
  
  onLoad() {
    const history = wx.getStorageSync('searchHistory') || []
    this.setData({ searchHistory: history })
  },
  
  onInput(e) {
    this.setData({ keyword: e.detail.value })
  },
  
  clearKeyword() {
    this.setData({ keyword: '', searchResult: null })
  },
  
  onSearch() {
    if (!this.data.keyword.trim()) return
    
    // 添加到搜索历史
    const history = [...new Set([this.data.keyword, ...this.data.searchHistory])]
    this.setData({ searchHistory: history.slice(0, 10) })
    wx.setStorageSync('searchHistory', history)
    
    // 模拟搜索
    this.setData({ isLoading: true })
    setTimeout(() => {
      const result = Array(5).fill().map((_, i) => ({
        _id: Date.now() + i,
        title: `${this.data.keyword}相关信息 ${i + 1}`,
        description: `这是关于${this.data.keyword}的搜索结果描述`,
        userName: i % 2 === 0 ? '王先生' : '赵女士',
        images: i % 3 === 0 ? ['https://via.placeholder.com/500x180'] : []
      }))
      this.setData({ searchResult: result, isLoading: false })
    }, 800)
  },
  
  onTagTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.setData({ keyword }, () => {
      this.onSearch()
    })
  },
  
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.setData({ keyword }, () => {
      this.onSearch()
    })
  },
  
  deleteHistory(e) {
    const index = e.currentTarget.dataset.index
    const history = [...this.data.searchHistory]
    history.splice(index, 1)
    this.setData({ searchHistory: history })
    wx.setStorageSync('searchHistory', history)
  }
})